#include "wl_file.h"

#include "wl_trace.h"

#include <sys/stat.h>
#include <unistd.h>

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

static void path_asc_to_ucs2(wl_char* path_asc, wl_uint16* path_ucs2) {
    wl_int32 i       = 0;
    wl_int32 pathlen = strlen(path_asc);

    for (i = 0; i < pathlen; i++) {
        if ('/' == path_asc[i]) {
            path_ucs2[i] = '\\';
        } else {
            path_ucs2[i] = path_asc[i];
        }
    }
    path_ucs2[i] = 0;
}

wl_int32 wl_mkdir(const wl_char* path) {
    if (-1 == wl_access(path, 0)) {
        return mkdir(path, 0666);
    }
    return 0;
}

wl_int32 wl_rmdir(const wl_char* path) {
    if (0 == wl_access(path, 0)) {
        return rmdir(path);
    }
    return 0;
}

wl_int32 wl_remove(const wl_char* path) {
    return remove(path);
}

wl_int32 wl_rename(const wl_char* src_path, const wl_char* dst_path) {
    return rename(src_path, dst_path);
}

wl_int32 wl_access(const wl_char* path, wl_int32 mode) {
    return access(path, mode);
}

WL_FHANDLE wl_fopen(const wl_char* path, wl_int32 flags) {
    return open(path, flags, 0666);
}

wl_int32 wl_fread(WL_FHANDLE fhandle, OUT void* buf, wl_uint32 count) {
    return read(fhandle, buf, count);
}

wl_int32 wl_fwrite(WL_FHANDLE fhandle, void* buf, wl_uint32 count) {
    return write(fhandle, buf, count);
}

wl_int32 wl_fclose(WL_FHANDLE fhandle) {
    return close(fhandle);
}

wl_int32 wl_fseek(WL_FHANDLE fhandle, wl_int32 offset, wl_int32 whence) {
    return lseek(fhandle, offset, whence);
}

wl_ssize wl_fsize(WL_FHANDLE fhandle) {
    struct stat statbuf;
    if (0 == fstat(fhandle, &statbuf)) {
        WLLOGT("fsize %d", statbuf.st_size);
        return statbuf.st_size;
    }
    return 0;
}

#ifdef __cplusplus
}
#endif /* __cplusplus */
